//
//  RootViewController.m
//  SelectionForYou
//
//  Created by qianfeng on 15-6-8.
//  Copyright (c) 2015年 朱共营. All rights reserved.
//

#import "RootViewController.h"
#import "AFNetworking.h"
#import "MyCell.h"
#import "MyModel.h"
#import "SecenddViewController.h"
//#import "SearchViewController.h"
#import "SettingViewController.h"
#import "JHRefresh.h"
#import "MMProgressHUD.h"
#import "MyControl.h"
#define kUrl @"http://apis.guokr.com/handpick/article.json?limit=20&ad=1&category=all&retrieve_type=by_since"
#define kUrlDownlod @"http://apis.guokr.com/handpick/article.json?retrieve_type=by_since&since=%ld&orientation=before"
#define kScreenSize [UIScreen mainScreen].bounds.size

@interface RootViewController ()<UISearchBarDelegate>
{
    NSString *_lastDate;
    NSInteger _k;
    BOOL isOver;
    BOOL _canClear;
}
@property(nonatomic)BOOL canClear;
@property(nonatomic,copy) NSString *lastDate;
@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.canClear=YES;
    [self addItemWithTitle:@"设置" target:self action:@selector(btnClick:) isLeft:YES];
    [self addItemWithTitle:@"刷新" target:self action:@selector(btnRefrash:) isLeft:NO];
    [self creatLaunchImageAnimation];
    self.title=@"猪哥精选";
   
    self.navigationController.navigationBar.translucent=NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"barbar"  ] forBarMetrics:UIBarMetricsDefault];
    _manager=[AFHTTPRequestOperationManager manager];
   _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
   _dataArr=[[NSMutableArray alloc] init];
    isOver=NO;
    NSLog(@"%d",isOver);
    
   
    [self creatTableView];
    //  [self downloadDataWithUrl:kUrl];
    [self firstDownload];
    [self creatRefreshView];
}

- (void)creatTableView{
    
    self.tabBarController.hidesBottomBarWhenPushed=NO;
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.tableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenSize.width, kScreenSize.height-64) style:UITableViewStylePlain];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MyCell" bundle:nil] forCellReuseIdentifier:@"MyCell"];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
 //
    UIImageView *viewImage=[[UIImageView alloc] initWithFrame:CGRectMake(0,0, kScreenSize.width, kScreenSize.height)];
    viewImage.image=[UIImage imageNamed: @"blackview"];
    [self.tableView setBackgroundView:viewImage];
    self.tableView.separatorStyle=UITableViewCellSelectionStyleNone;
    [self.view addSubview:self.tableView];
    
    
}
- (void)creatLaunchImageAnimation{
    UIImageView *starView=[MyControl creatImageViewWithFrame:self.view.bounds imageName:[NSString stringWithFormat:@"Defaultretein%u",arc4random()%7+1]];
    [self.view addSubview:starView];
    [UIView animateWithDuration:10 animations:^{
        starView.alpha=0;
    }completion:^(BOOL finished) {
        [starView removeFromSuperview];
    }];

    NSLog(@"122");
}
//导航左右按钮
- (void)addItemWithTitle:(NSString *)title target:(id)target action:(SEL)action isLeft:(BOOL)isLeft{
    if (isLeft) {
        UIButton *button=[MyControl creatButtonWithFrame:CGRectMake(0, 0, 50, 30) target:target sel:action tag:100 image:@"buttonbar_back" title:title];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:button];
       
        self.navigationItem.leftBarButtonItem = item;
    }else{
        
       UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(btnRefrash:)];
       
        self.navigationItem.rightBarButtonItem = rightButton;

    }

}

- (void)btnRefrash:(UIButton *)btn{
    NSLog(@"zaishuxin");
    [self.tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
   //
    if (isOver) {
        if (_k>12) {
            
           
            [self addTaskUrl:kUrl isRefresh:NO];
            self.canClear=YES;
            _k=0;
        }else{
            self.canClear=YES;
            
            
            [self addTaskUrl:kUrl isRefresh:NO];
            
            UIAlertView *alter=[[UIAlertView alloc] initWithTitle:@"亲" message:@"已经是最新,再刷,奴家做不到" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alter show];
           
            
        }

    }else{
        UIAlertView *alter=[[UIAlertView alloc] initWithTitle:@"警告" message:@"刷新失败,请检查网络" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alter show];
    
    }
    
}

- (void)btnClick:(UIButton *)ntb{
    SettingViewController *set=[[SettingViewController alloc] init] ;
    
    [self.navigationController pushViewController:set animated:YES];
   // [self presentViewController:set animated:YES completion:nil];

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
 
    
        return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
        MyModel *model=_dataArr[indexPath.row];
    
        MyCell *cell=[tableView dequeueReusableCellWithIdentifier:@"MyCell" forIndexPath:indexPath];
        [cell showDataWithModel:model];
     UIView *view = [[UIView alloc ]initWithFrame:CGRectMake(0, 0, kScreenSize.width, 10)];
       view.backgroundColor=[UIColor colorWithRed:238/256.0f green:238/256.f blue:238/256.f alpha:1];
    [cell.contentView addSubview:view];
    _k++;
    NSLog(@"%ld",_k);
    
        return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MyModel *model=_dataArr[indexPath.row];
  
    
   SecenddViewController *secend=[[SecenddViewController alloc] init];
    secend.idd=model.id;
    secend.headline_img_tb=model.headline_img_tb;
    secend.link_v2=model.link_v2;
    secend.titleHose=model.title;
    [self.navigationController pushViewController:secend animated:YES];
  
    

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return 141;
}
- (void)firstDownload{
    self.isRefreshing=NO;
    self.isLoadMoring=NO;
    [self addTaskUrl:kUrl isRefresh:NO];
   
}
- (void)addTaskUrl:(NSString *)url isRefresh:(BOOL)isRefresh{
    
     NSLog(@"%@",url);
   
    __weak typeof (self) weakSelf = self;
    
    if (_isRefreshing) {
        return;
    }
    _isLoadMoring=YES;
    _isRefreshing=YES;
    
    [_manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (_canClear) {
            NSLog(@"%d",_isRefreshing);
            [self.dataArr removeAllObjects];
            
        }
        
        NSLog(@"刷新成功");
       
        if (responseObject) {
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *arr=dict[@"result"];
             int i=0;
            for (NSDictionary *appDict in arr) {
                i++;
                MyModel *model=[[MyModel alloc] init];
                [model setValuesForKeysWithDictionary:appDict];
                [weakSelf.dataArr addObject:model];
               // NSLog(@"%d",i);
                if (i==arr.count) {
                   
                    weakSelf.lastDate=model.date_picked;
                     NSLog(@"%@",weakSelf.lastDate);
                  //./  NSLog(@"%@");
                }
                
            }
            isOver=YES;
            [weakSelf.tableView reloadData];
            
            [weakSelf endRefreshing];
 //           [MMProgressHUD dismissWithSuccess:@"恭喜你" title:@"刷新成功"];
            NSLog(@"%d",_isLoadMoring);
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"刷新下载失败");
        isOver=NO;
        [weakSelf endRefreshing];
  //      [MMProgressHUD dismissWithError:@"下载失败" title:@"警告"];
    }];

}
- (void)creatRefreshView{
    __weak typeof(self)weakSelf=self;
    NSLog(@"1");
    [self.tableView addRefreshHeaderViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        if (weakSelf.isRefreshing) {
            return ;
        }
       
        weakSelf.isRefreshing = NO;
        weakSelf.canClear=YES;
        
       // [weakSelf downloadDataWithUrl:kUrl];
        [weakSelf addTaskUrl:kUrl isRefresh:NO];
    }];

    
    
    [self.tableView addRefreshFooterViewWithAniViewClass:[JHRefreshCommonAniView class] beginRefresh:^{
        //上啦加载更多
     //   NSLog(@"%hhd",_isLoadMoring);
        if (weakSelf.isLoadMoring) {
             [weakSelf endRefreshing];
            return ;
            
           
        }
        
         NSString *str=[NSString stringWithFormat:kUrlDownlod,(long)weakSelf.lastDate.integerValue];
        NSLog(@"%@",str);
       // NSLog(@"%d",self.lastDate.intValue);
        weakSelf.canClear=NO;
        weakSelf.isLoadMoring=NO;
        
       
        [weakSelf addTaskUrl:str isRefresh:NO];
        weakSelf.lastDate=nil;
       
    }];

   
    
    
}
- (void)endRefreshing{
    if (self.isLoadMoring) {
        self.isLoadMoring=NO;
        [self.tableView footerEndRefreshing];
    }
    if (self.isRefreshing) {
        self.isRefreshing =NO;
        [self.tableView headerEndRefreshingWithResult:JHRefreshResultSuccess];
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/





@end
